//
//  DCADView.m
//  DCTest
//
//  Created by Joinwe on 16/7/7.
//  Copyright © 2016年 Joinwe. All rights reserved.
//

#import "DCADView.h"

@interface DCADView(){
    NSTimer *_countDownTimer;
}

/**是否点击*/
@property (nonatomic, copy)   NSString   *isClick;
/**倒计时总长*/
@property (nonatomic, assign) NSInteger secondsCount;

@end


@implementation DCADView


- (instancetype)initWithWindow:(UIWindow *)window andType:(DCADType)type andImageUrl:(NSString *)imageUrl{
    self = [super init];
    if (self) {
        self.window = window;
        _secondsCount = 0;
        [window makeKeyAndVisible];
        //获取启动图片
        CGSize viewSize = window.bounds.size;
        //横屏请修改这里的设置 @"Landscape"
        NSString *viewOrientation = @"Portrait";
        
        NSString *launchImageName = nil;
        
        NSArray *imagesDictArray = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
        
        for (NSDictionary *dict in imagesDictArray) {
            CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
            if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:@"UILaunchImageOrientation"]) {
                launchImageName = dict[@"UILaunchImageName"];
            }
        }
        
        UIImage *launchImage = [UIImage imageNamed:launchImageName];
        self.backgroundColor = [UIColor colorWithPatternImage:launchImage];
        self.frame = CGRectMake(0, 0, kDeviceWidth, kDeviceHeight);
        if (type == FullScreenDCADType) {
            self.DCADImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, kDeviceHeight)];
        }else{
            self.DCADImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, kDeviceHeight - kDeviceWidth / 3)];
        }
        
        self.skipButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.skipButton.frame = CGRectMake(kDeviceWidth - 70, 20, 60, 30);
        self.skipButton.backgroundColor = [UIColor brownColor];
        self.skipButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [self.skipButton addTarget:self action:@selector(skipButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self.DCADImageView addSubview:self.skipButton];
        
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.skipButton.bounds byRoundingCorners:UIRectCornerBottomRight | UIRectCornerTopRight cornerRadii:CGSizeMake(15, 15)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = self.skipButton.bounds;
        maskLayer.path = maskPath.CGPath;
        self.skipButton.layer.mask = maskLayer;
        
        
        SDWebImageManager *manager = [SDWebImageManager sharedManager];
//        [manager loadImageWithURL:[NSURL URLWithString:imageUrl] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
//            
//        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
//            if (image) {
//                [self.DCADImageView setImage:[self imageCompressForWidth:image targetWidth:kDeviceWidth]];
//            }
//        }];
        
        [manager loadImageWithURL:[NSURL URLWithString:imageUrl] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            if (image) {
                [self.DCADImageView setImage:[self imageCompressForWidth:image targetWidth:kDeviceWidth]];
            }
        }];
        
        
        self.DCADImageView.tag = 1101;
        self.DCADImageView.backgroundColor = [UIColor redColor];
        [self addSubview:self.DCADImageView];
        
        //添加点击手势
        UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(activiTap:)];
        
        self.DCADImageView.userInteractionEnabled = YES;
        [self.DCADImageView addGestureRecognizer:tapGR];
        
        //添加动画
        CABasicAnimation *animation = [CABasicAnimation animation];
        animation.duration = 0.8;
        animation.fromValue = [NSNumber numberWithFloat:0.0];
        animation.toValue = [NSNumber numberWithFloat:0.8];
        
        
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
        
        
        [self.DCADImageView.layer addAnimation:animation forKey:@"animateOpacity"];
        
        _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
        
        [self.window addSubview:self];
        
        
    }
    return self;
}


#pragma mark - 点击广告
- (void)activiTap:(UITapGestureRecognizer*)recognizer{
    _isClick = @"1";
    [self startcloseAnimation];
}

#pragma mark - 开启关闭动画
- (void)startcloseAnimation{
    CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opacityAnimation.duration = 0.5;
    opacityAnimation.fromValue = [NSNumber numberWithFloat:1.0];
    opacityAnimation.toValue = [NSNumber numberWithFloat:0.3];
    opacityAnimation.removedOnCompletion = NO;
    opacityAnimation.fillMode = kCAFillModeForwards;
    
    [self.DCADImageView.layer addAnimation:opacityAnimation forKey:@"animateOpacity"];
    [NSTimer scheduledTimerWithTimeInterval:opacityAnimation.duration
                                     target:self
                                   selector:@selector(closeAddImgAnimation)
                                   userInfo:nil
                                    repeats:NO];
    
}


- (void)skipButtonClick{
    _isClick = @"2";
    [self startcloseAnimation];
}

#pragma mark - 关闭动画完成时处理事件
-(void)closeAddImgAnimation
{
    [_countDownTimer invalidate];
    _countDownTimer = nil;
    self.hidden = YES;
    self.DCADImageView.hidden = YES;
    self.hidden = YES;
    if ([_isClick integerValue] == 1) {
        if (self.clickBlock) {//点击广告
            self.clickBlock(1100);
        }
    }else if([_isClick integerValue] == 2){
        if (self.clickBlock) {//点击跳过
            self.clickBlock(1101);
        }
    }else{
        if (self.clickBlock) {//点击跳过
            self.clickBlock(1102);
        }
    }

}

- (void)onTimer {
    if (_DCADTime == 0) {
        _DCADTime = 6;
    }
    if (_secondsCount < _DCADTime) {
        _secondsCount++;
        [self.skipButton setTitle:[NSString stringWithFormat:@"%ld | 跳过",_secondsCount] forState:UIControlStateNormal];
    }else{
        [_countDownTimer invalidate];
        _countDownTimer = nil;
        [self startcloseAnimation];
        
    }
}


#pragma mark - 指定宽度按比例缩放
- (UIImage *)imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = height / (width / targetWidth);
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        if(widthFactor > heightFactor){
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            
        }else if(widthFactor < heightFactor){
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    //    UIGraphicsBeginImageContext(size);
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        NSLog(@"scale image fail");
    }
    
    UIGraphicsEndImageContext();
    return newImage;
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
